<?php

namespace Modules\Admin\Http\Controllers\ActivationCodes;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\ActivationCodeUsage;
use Modules\Common\Models\ActivationCodeLogs;
use Modules\Common\Models\ActivationCodes;
use Modules\Common\Models\SubscriptionRecords;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;


class Create
{
    /**
     * @Route(path=/api/admin/activation-code  method=post)
     */
    public function index()
    {
        $adminUserIdDefault = auth('api')->user()->id;
        $eidDefault = auth('api')->user()->eid; 
        $sidDefault = auth('api')->user()->sid; 
        $quantity = request('quantity'); // 获取请求中的数量参数
        $expire_time = request('expire_time'); // 获取请求中的过期时间
        $subscription_type_id = request('subscription_type_id');
    
        // 参数验证
        if (empty($quantity) || empty($expire_time) || empty($subscription_type_id)) {
            return Api::fail('参数缺失或无效', 400);
        }
    
        DB::beginTransaction();
        try {
            for ($i = 0; $i < $quantity; $i++) {
                $activationCodes = new ActivationCodes();
                $activationCodes->code = $this->generateActivationCode(12);
                $activationCodes->status = 1; // 待激活
                $activationCodes->expire_time = date('Y-m-d 23:59:59',strtotime($expire_time));
                $activationCodes->subscription_type_id = $subscription_type_id;
                $activationCodes->admin_user_id = $adminUserIdDefault;
                $activationCodes->eid = $eidDefault;
                $activationCodes->sid = $sidDefault;
                $activationCodes->create_time = date('Y-m-d H:i:s');
                $activationCodes->created_at = date('Y-m-d H:i:s');
                $activationCodes->save();
            }
    
            // 做一个统计
            $activationCodeLogs = new ActivationCodeLogs();
            $activationCodeLogs->subscription_type_id = $subscription_type_id;
            $activationCodeLogs->created_codes = $quantity;
            $activationCodeLogs->admin_user_id = $adminUserIdDefault;
            $activationCodeLogs->eid = $eidDefault;
            $activationCodeLogs->sid = $sidDefault;
            $activationCodeLogs->save();
    
            DB::commit();
            return Api::success($activationCodeLogs);
        } catch (\Exception $e) {
            DB::rollBack();
            return Api::fail($e->getMessage(), 500);
        }
    }
    
    public function generateActivationCode($length = 12) {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $activationCode = '';
        for ($i = 0; $i < $length; $i++) {
            $randomIndex = mt_rand(0, $charactersLength - 1);
            $activationCode .= $characters[$randomIndex];
        }
        return $activationCode;
    }

}